import java.util.Scanner;
import org.jmusixmatch.MusixMatch;
import org.jmusixmatch.MusixMatchException;
import org.jmusixmatch.entity.lyrics.Lyrics;
import org.jmusixmatch.entity.track.Track;
import org.jmusixmatch.entity.track.TrackData;


public class CrawlLyrics {
	
	static String msdID;
	static String trackName;
	static String artistName;
	static String[] result = new String[3];
	static String apiKey = "b246d9bdf8e7613401289b56a58edeb6";
	static MusixMatch musixMatch = new MusixMatch(apiKey);
	static PrintLyrics printlyrics;
	static Lyrics lyrics;
	static int trackID;
	
	public static void main(String[] args) {
		
		DBConnection.getConnection();
		printlyrics = new PrintLyrics();
		
		Scanner numbers = new Scanner(System.in);
		int start;
		int end;
		
		//select range of lyrics from track_meta.db
		System.out.println("Enter start ID");
		start = numbers.nextInt();
		System.out.println("Enter end ID");
		end = numbers.nextInt();
		
		for(int currentTrack = start; currentTrack <= end; currentTrack++) {
			
			//get MSD track ID,  title and artist from track_metadata.db
			//result[0] = MSD track ID
			//result[1] = trackName
			//result[2] = artistName
			result = DBConnection.insertQuery(currentTrack);
			msdID = result[0];
			trackName = result[1];
			artistName = result[2];
			
			try {
				//get track by searching trackName and artistName from track_metadata.db file
				Track track = null;
				track = musixMatch.getMatchingTrack(trackName, artistName);
				
				//get trackID to search lyrics
				TrackData data = track.getTrack();
				trackID = data.getTrackId();
				// System.out.println("Current Track: " + currentTrack + " TrackID: " + trackID);
				// System.out.println("TrackName: " + trackName + " Artist: " + artistName);
				Lyrics lyrics = null;
				lyrics = musixMatch.getLyrics(trackID);
		
				/**save lyrics to txt file
				 currentTrack -> row number of entry in track_metadata.db
				 msID -> ID from Million Song Database
				 trackName -> title of the song
				 artistName -> artist of the song
				 lyrics.getLyricsBody -> lyrics Text
				**/
				printlyrics.PrintLyrics(currentTrack, msdID, trackName, artistName, lyrics.getLyricsBody());
				/**
				System.out.println("Lyrics ID       : "     + lyrics.getLyricsId());
				System.out.println("Lyrics Language : "     + lyrics.getLyricsLang());
				System.out.println("Lyrics Body     : "     + lyrics.getLyricsBody());
				System.out.println("Script-Tracking-URL : " + lyrics.getScriptTrackingURL());
				System.out.println("Pixel-Tracking-URL : "  + lyrics.getPixelTrackingURL());
				System.out.println("Lyrics Copyright : "    + lyrics.getLyricsCopyright());
				**/
			} catch(MusixMatchException e) {
				//e.printStackTrace();
			} catch(NullPointerException n) {
				//n.printStackTrace();
			}
		} //end for-loop
		DBConnection.closeConnection();
	}
	
} //end of class
